package com.yc.io.netty.demo2;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 处理网络事件
 * @author yuancan
 *
 */
public class MyServerHandler extends ChannelInboundHandlerAdapter {

	/**
	 * 收到客户端消息事件
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		byte[] reg = new byte[buf.readableBytes()];
		buf.readBytes(reg);
		String body = new String(reg, "utf-8");
		System.out.println(Thread.currentThread().getName() + ", This server receive order: " + body);
		
		//创建回复消息
		String res = "I am server , 消息接收成功";
		ByteBuf resByteBuf = Unpooled.copiedBuffer(res.getBytes());
		//用ctx写出去
		ctx.write(resByteBuf);
		
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}

	
}
